import 'dart:convert';

import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:szwf/page/out/index.dart';
import 'package:szwf/page/put/index.dart';
import 'package:szwf/utils/common_toast.dart';
import 'package:szwf/utils/dio_http.dart';

class BarCodeScanPage extends StatefulWidget {
  BarCodeScanPage({Key key}) : super(key: key);

  @override
  _BarCodeScanPageState createState() => _BarCodeScanPageState();
}

class _BarCodeScanPageState extends State<BarCodeScanPage> {


  var _content= TextEditingController();
  final _formKey = GlobalKey<FormState>();
  String qrNumber;
  scan() async {
    var options = ScanOptions(
      strings: {
        "cancel": "关闭",
        "flash_on": "开灯",
        "flash_off": "关灯",
      },
    );

    ScanResult result = await BarcodeScanner.scan(options: options);
    setState(() {
      _content.text = result.rawContent;
    });
  }

  onSave (String type) async {


      //成功
      CommonToast.showToast('正在查询!');
      if(type == '出库'){
        //出库
        const url = '/wfgl/entrancewarehouse/findOneByQrNumber';
        var params = {
          "qrNumber":_content.text,
        };
        var res = await DioHttp.of(context).get(url,params);
        var resString = json.decode(res.toString());
        if(resString['rc'] == 0){
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return OutPage();
              },
              settings: RouteSettings(
                arguments: resString['ret'],
              ), // 传参
              fullscreenDialog: true,
            ),
          );
        }else{
          CommonToast.showToast(resString['err']);
        }

      }else{
        //入库
        const url = '/wfgl/qrcode/findOneByQrNumber';
        var params = {
          "qrNumber":_content.text,
        };
        var res = await DioHttp.of(context).get(url,params);
        var resString = json.decode(res.toString());

        if(resString['rc'] == 0){
          var data = resString['ret'];
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (context) {
                return PutPage();
              },
              settings: RouteSettings(
                arguments: data,
              ), // 传参
              fullscreenDialog: true,
            ),
          );
        }else{
          CommonToast.showToast(resString['err']);
        }

      }
  }

  @override
  Widget build(BuildContext context) {
    Map typePage = ModalRoute.of(context).settings.arguments;
    return Scaffold(
        resizeToAvoidBottomInset:false,
      appBar: AppBar(
        title: Center(
          child: Text('点击扫码${typePage["name"]}'),
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.camera_alt),
            onPressed: () {
              scan();
            },
          ),
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          picAndTextButton('assets/saoma.gif','出库'),
          Padding(
          padding: EdgeInsets.all(40.0),
           child:  Form(
            key: _formKey,
            child: Column(
//              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[

                TextFormField(
                  textAlign: TextAlign.left,

                  controller: TextEditingController.fromValue(TextEditingValue(
                    // 设置内容
                      text: _content.text,
                      // 保持光标在最后
                      selection: TextSelection.fromPosition(TextPosition(
                          affinity: TextAffinity.downstream,
                          offset: _content.text.length))
                  )
                  ),
                  onChanged: (value){
                    _content.text=value;
                  },
                  decoration: const InputDecoration(

                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.blue),
                      ),
                      enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.grey),
                      ),
//                      prefixIcon: Icon(Icons.supervised_user_circle,color: Colors.blue,),
                      hintText: '请扫码或填写条码编号',
                      hintStyle: TextStyle(
                          fontSize: 12.0,
                          color: Colors.grey
                      )
                  ),
                  validator: (value) {
                    if (value.isEmpty) {
                      return '条码编号为必填参数!';
                    }
                    return null;
                  },
                ),
                SizedBox(
                  height: 20.0,
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      child: Container(
                        height: 35,
                        child: RaisedButton(
                          color: Colors.blue,
                          textColor: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(25),
                          ),
                          onPressed: () {
                            // Validate will return true if the form is valid, or false if
                            // the form is invalid.
                            if (_formKey.currentState.validate()) {
                              // Process data.
                              onSave(typePage["name"].toString(),);
                            }
                          },
                          child: Text('确定'),
                        ),
                      ),
                    )
                  ],
                ),

              ],
            ),
          ),
        )

        ],
      )
    );
  }

  Widget picAndTextButton(String imgpath,String text) {
    return Padding(
        padding: EdgeInsets.all(40.0),
        child: Center(
          child: Container(
            width: 160.0,
            height: 160,
            decoration: BoxDecoration(
              color: Colors.white,
              image: DecorationImage(
                  image: AssetImage(imgpath),
                  fit: BoxFit.fill
              ),
            ),
            alignment: Alignment.center,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    height: double.infinity,
                    child: FlatButton(
                      textColor: Colors.white,
                      onPressed: () {
                        scan();
                      },
                    ),
                  ),
                )
              ],
            ),
          ),
        )
    );
  }
}